package demo1;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoClient {
    private Socket  socket = null ;

    public TcpEchoClient(String serverIp , int serverPort) throws IOException {
        //socket和服务器建立连接,需要告诉socket 服务器在哪里,
        //具体建立连接的细节,就交由内核处理,不需要我们管
        // 创建socket时,把服务器的信息给socket
        this.socket = new Socket(serverIp , serverPort); // 当我们new出对象时,内核就帮我们进行连接
    }
    public void start(){
        System.out.println("客户端启动");
        Scanner scan = new Scanner(System.in) ;
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()){
            Scanner scanResponse = new Scanner(inputStream) ;
            while (true){
                 //1.在控制台读取请求
                System.out.println("输入请求-> ");
                String request = scan.next() ;
                //2. 把请求发送给服务器
                PrintWriter writer = new PrintWriter(outputStream) ;
                // 使用println ,为了发生的请求也带有\n换行
                writer.println(request);
                writer.flush();
                //3. 读取响应
                String response = scanResponse .next() ;
                //4.打印响应
                System.out.println(response);
             }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient client  = new TcpEchoClient("127.0.0.1" , 9090);
        client.start();
    }
}
